package com.grouuu.update;

import com.grouuu.event.TimerEvent;
import starling.core.Starling;
import starling.events.EnterFrameEvent;
import starling.events.Event;
import starling.events.EventDispatcher;

/**
 * ...
 * @author Grouuu
 */

class Timer 
{
	private var dispatcher:EventDispatcher;
	
	public function new() 
	{
		init();
	}
	
	private function init():Void
	{
		dispatcher = new EventDispatcher();
	}
	
	// CONTROLS ///////////////////////////////////////////////////////////////////////////////
	
	public function addListener(listener:ITimer):Void
	{
		dispatcher.addEventListener(TimerEvent.ON_UPDATE, listener.update);
		dispatcher.addEventListener(TimerEvent.ON_START, listener.start);
		dispatcher.addEventListener(TimerEvent.ON_STOP, listener.stop);
	}
	
	public function removeListener(listener:ITimer):Void
	{
		dispatcher.removeEventListener(TimerEvent.ON_UPDATE, listener.update);
		dispatcher.removeEventListener(TimerEvent.ON_START, listener.start);
		dispatcher.removeEventListener(TimerEvent.ON_STOP, listener.stop);
	}
	
	public function start():Void
	{
		dispatcher.dispatchEvent(new Event(TimerEvent.ON_START));
		
		Starling.current.stage.addEventListener(EnterFrameEvent.ENTER_FRAME, onFrame);
	}
	
	public function stop():Void
	{
		Starling.current.stage.removeEventListener(EnterFrameEvent.ENTER_FRAME, onFrame);
		
		dispatcher.dispatchEvent(new Event(TimerEvent.ON_STOP));
	}
	
	// EVENTS /////////////////////////////////////////////////////////////////////////////////
	
	private function onFrame(event:EnterFrameEvent):Void
	{
		dispatcher.dispatchEvent(new TimerEvent(TimerEvent.ON_UPDATE, event.passedTime));
	}
	
}